package com.cet.designapplication.decorator.strategy.factory;

import com.cet.designapplication.decorator.strategy.ScoreAndRegBagSendStrategy;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 策略工厂
 * @author NSOC
 */
@Component
public class ScoreAndRegBagSendHandlerFactory implements InitializingBean, ApplicationContextAware {


    private static final
    Map<Integer, ScoreAndRegBagSendStrategy> SCORE_AND_REGBAG_SEND_HANDLER_MAP = new HashMap<>(8);


    private ApplicationContext appContext;


    /**
     * 根据提交类型获取对应的处理器
     *
     * @param serviceLevel 服务降级
     * @return 提交类型对应的处理器
     */
    public ScoreAndRegBagSendStrategy getHandler(Integer serviceLevel) {
        return SCORE_AND_REGBAG_SEND_HANDLER_MAP.get(serviceLevel);
    }


    @Override
    public void afterPropertiesSet() {
        // 将 Spring 容器中所有的 FormSubmitHandler 注册到 FORM_SUBMIT_HANDLER_MAP
        appContext.getBeansOfType(ScoreAndRegBagSendStrategy.class)
                  .values()
                  .forEach(handler -> SCORE_AND_REGBAG_SEND_HANDLER_MAP.put(handler.getServiceLevel(), handler));
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        appContext = applicationContext;
    }
}